<template>
  <div
    :jiBieArr="[2]"
    :tipArr="[, '数据导入只对站点级别开放', '', , '']"
    style="padding: 15px"
  >
    <el-form
      :model="queryForm"
      ref="queryForm"
      :inline="true"
      label-width="68px"
      style="margin-top: 20px"
      class="globalSerchFormStyle"
    >
      <el-row>
        <el-col :span="6">
          <el-form-item label="手机号" prop="phoneNumber">
            <el-input
              v-model="queryForm.phoneNumber"
              placeholder="请输入手机号"
              clearable
              size="small"
              style="width: 190px"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row class="global_el_rowStyle" :gutter="10">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-refresh"
          size="mini"
          plain
          @click="resetQuery"
          >重置</el-button
        >
      </el-col>
      <el-col :span="1.5"></el-col>
    </el-row>

    <!--主要表格-->
    <el-table :data="importList" stripe>
      <af-table-column
        label="手机"
        align="left"
        prop="phoneNumber"
        fixed="left"
      />
      <af-table-column label="积分" align="left" prop="integral" />
      <af-table-column
        label="电子卡类型"
        align="left"
        prop="memberGrade"
        width="160px"
      >
        <template slot-scope="scope">
          {{ translateCardToName(scope.row) }}
        </template>
      </af-table-column>
      <af-table-column label="电子卡余额" align="left" prop="balance" />
      <af-table-column
        label="会员等级"
        align="left"
        prop="memberGrade"
        width="160px"
      >
        <template slot-scope="scope">
          {{ translateGradeToName(scope.row) }}
        </template>
      </af-table-column>
      <af-table-column label="标签" align="left" prop="labelId" width="160px">
        <template slot-scope="scope">
          {{ translateLabelToName(scope.row) }}
        </template>
      </af-table-column>
      <af-table-column
        label="优惠券领取方式"
        align="left"
        prop="couponIssueId"
        width="160px"
      >
        <template slot-scope="scope">
          {{ translateIssueToName(scope.row) }}
        </template>
      </af-table-column>
    </el-table>
    <pagination
      v-show="total > 1"
      :total="total"
      :pageSizes="[10, 50, 100, 200]"
      :page.sync="queryForm.pageNum"
      :limit.sync="queryForm.pageSize"
      @pagination="getList"
    />

    <!--拉入前提示框-->
    <el-dialog
      :title="'强拉入' + handleTypeName[handleType]"
      :visible.sync="confirmDialog"
      width="750px"
      append-to-body
    >
      <div class="ml-5">
        无论当前用户此刻是否已经有{{ handleTypeName[handleType] }}，
        点击确认按钮后，会立刻将选中用户拉入新的
        {{ handleTypeName[handleType] }}~
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmitLable" size="small"
          >确 定</el-button
        >
        <el-button @click="cancelSubmitLabel" size="small">取 消</el-button>
      </div>
    </el-dialog>
    <!--导入 表格反馈-->
    <el-dialog
      :title="'结果反馈'"
      :visible.sync="tipOpen"
      width="600px"
      append-to-body
      status-icon
      @close="getList"
    >
      <div v-html="tipContent">
        {{ tipContent }}
      </div>
    </el-dialog>

    <!-- 新增单条导入 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="600px"
      append-to-body
      status-icon
    >
      <el-form ref="createForm" :model="createForm" label-width="180px">
        <el-form-item
          label="手机号"
          prop="phoneNumber"
          :rules="{
            required: true,
            message: '手机号不能为空',
            trigger: 'blur',
          }"
        >
          <input
            type="text"
            class="form-control"
            v-model="createForm.phoneNumber"
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="积分余额" prop="integral">
          <input
            type="text"
            class="form-control"
            v-model.number="createForm.integral"
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="电子卡类型" prop="cardType">
          <el-radio-group v-model="createForm.cardType">
            <div>
              <el-radio label="1">汽油卡</el-radio>
              <el-radio label="2">柴油卡</el-radio>
            </div>
            <div>
              <el-radio label="3">LNG卡</el-radio>
              <el-radio label="4">CNG卡</el-radio>
            </div>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="电子卡余额" prop="balance">
          <input
            type="text"
            class="form-control"
            v-model.number="createForm.balance"
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="等级" prop="memberGrade">
          <el-select v-model="createForm.memberGrade" placeholder="请选择">
            <el-option :label="'暂不选择'" :value="''"> </el-option>
            <el-option
              v-for="ele in gradeList"
              :key="ele.id"
              :label="ele.grade"
              :value="ele.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标签" prop="labelId">
          <el-select v-model="createForm.labelId" placeholder="请选择">
            <el-option :label="'暂不选择'" :value="''"> </el-option>
            <el-option
              v-for="ele in labelList"
              :key="ele.id"
              :label="ele.labelName"
              :value="ele.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="优惠券领取方式" prop="couponIssueId">
          <el-select v-model="createForm.couponIssueId" placeholder="请选择">
            <el-option :label="'暂不选择'" :value="''"> </el-option>
            <el-option
              v-for="ele in issueList"
              :key="ele.id"
              :label="ele.issueRemark"
              :value="ele.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--多条导入的弹窗-->
    <el-dialog
      title="由Excel导入的数据"
      :visible.sync="tempImportDialog"
      append-to-body
      status-icon
      width="80vw"
    >
      <el-table :data="tempImportList" class="mt-5" style="margin-bottom: 10px">
        <af-table-column label="手机" align="left" prop="phoneNumber" />
        <af-table-column
          label="积分"
          align="left"
          prop="integral"
          width="160px"
        >
          <template slot-scope="scope">
            {{ translateIntegralToInt(scope.row) }}
          </template>
        </af-table-column>
        <af-table-column
          label="电子卡类型"
          align="left"
          prop="memberGrade"
          width="160px"
        >
          <template slot-scope="scope">
            {{ translateCardToName(scope.row) }}
          </template>
        </af-table-column>
        <af-table-column label="电子卡余额" align="left" prop="balance" />
        <af-table-column
          label="电子卡余额"
          align="left"
          prop="balance"
          width="160px"
        >
          <template slot-scope="scope">
            {{ translateBalanceToFloat(scope.row) }}
          </template>
        </af-table-column>
        <af-table-column
          label="会员等级"
          align="left"
          prop="memberGrade"
          width="160px"
        >
          <template slot-scope="scope">
            {{ translateGradeToName(scope.row) }}
          </template>
        </af-table-column>
        <af-table-column label="标签" align="left" prop="labelId" width="160px">
          <template slot-scope="scope">
            {{ translateLabelToName(scope.row) }}
          </template>
        </af-table-column>

        <af-table-column
          label="优惠券领取方式"
          align="left"
          prop="couponIssueId"
          width="160px"
        >
          <template slot-scope="scope">
            {{ translateIssueToName(scope.row) }}
          </template>
        </af-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitExcel">确 定</el-button>
        <el-button @click="cancelExcel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import excel from "@/utils/excel";
import {
  getIssueList,
  getGradeList,
  getLabelList,
  importExcel,
  getImportList,
  updateImportList,
  delImportList,
  upImport,
} from "@/api/preData";

export default {
  name: "PreData_ImportedData",
  data() {
    return {
      queryForm: {
        pageNum: 1,
        pageSize: 10,
        phoneNumber: "",
        importFlag: "1",
      },
      tipOpen: false,
      tipContent: "",
      title: "",
      open: false,
      // 总条数
      total: 0,
      importList: [],
      tempImportList: [],
      selectedImport: [],
      confirmDialog: false,
      tempImportDialog: false,
      createForm: {
        phoneNumber: "",
        integral: 0,
        cardType: "1",
        balance: 0,
        memberGrade: "",
        labelId: "",
        couponIssueId: "",
      },
      issueList: [],
      labelList: [],
      gradeList: [],
      handleTypeName: ["等级", "标签", "优惠券领取方式"],
      handleType: 1, // 0 等级 1 标签 2 优惠券领取方式
      tempId: "",
      tempArr: [],
    };
  },
  computed: {},
  created() {
    this.init();
  },
  methods: {
    init() {
      this.getList();

      // getIssueList()
      //   .then((res) => {
      //     if (res.code == 200) {
      //       if (res.rows == null) {
      //         this.issueList = [];
      //       } else {
      //         this.issueList = res.rows;
      //       }
      //     } else {
      //       throw new Error("");
      //     }
      //   })
      //   .catch((err) => {
      //     this.msgError("拉取优惠券领取方式失败~");
      //   });
      getLabelList()
        .then((res) => {
          if (res.code == 200) {
            if (res.rows == null) {
              this.labelList = [];
            } else {
              this.labelList = res.rows;
            }
          } else {
            throw new Error("");
          }
        })
        .catch((err) => {
          this.msgError("拉取标签列表失败~");
        });
      getGradeList()
        .then((res) => {
          if (res.code == 200) {
            if (res.rows == null) {
              this.gradeList = [];
            } else {
              this.gradeList = res.rows;
            }
          } else {
            throw new Error("");
          }
        })
        .catch((err) => {
          this.msgError("拉取等级列表失败~");
        });
    },
    translateIntegralToInt(row) {
      const integral = +row.integral;
      if (isNaN(integral)) {
        row.integral = 0;
        return 0;
      } else {
        row.integral = integral;
        return integral;
      }
    },
    translateBalanceToFloat(row) {
      const balance = +row.balance;
      if (isNaN(balance)) {
        row.balance = 0;
        return 0;
      } else {
        row.balance = balance;
        return balance;
      }
    },
    translateIssueToName(row) {
      const id = row.couponIssueId;
      const issue = this.issueList.find((ele) => {
        return ele.id == id;
      });
      if (issue == undefined) {
        row.couponIssueId = undefined;
        return "----";
      }
      return issue.issueRemark;
    },
    translateGradeToName(row) {
      const id = row.memberGrade;
      const grade = this.gradeList.find((ele) => {
        return ele.id == id;
      });
      if (grade == undefined) {
        row.memberGrade = undefined;
        return "----";
      }
      return grade.grade;
    },
    translateLabelToName(row) {
      const id = row.labelId;
      const label = this.labelList.find((ele) => {
        return ele.id == id;
      });
      if (label == undefined) {
        row.labelId = undefined;
        return "----";
      }
      return label.labelName;
    },
    translateCardToName(row) {
      const id = row.cardType;
      const typeObj = {
        0: "通用卡",
        1: "汽油卡",
        2: "柴油卡",
        3: "LNG卡",
        4: "CNG卡",
      };

      const type = typeObj[id];
      if (type == undefined) {
        row.cardType = "";
        return "----";
      }
      return type;
    },
    submitForm() {
      this.$refs["createForm"].validate((valid) => {
        if (valid) {
          if (!this.createForm.excelId) {
            importExcel([this.createForm])
              .then((res) => {
                this.open = false;
                this.tipOpen = true;
                this.tipContent = res.msg;
              })
              .catch(() => {
                this.msgError("导入失败，请刷新重试~");
              });
          } else {
            upImport(this.createForm).then((res) => {
              this.open = false;
              this.msgSuccess("修改成功");
            });
          }
        }
      });
    },
    cancel() {
      this.open = false;
    },
    batchAdd() {
      let upBut = document.getElementById("upload_file");
      upBut.click();
    },
    handleAdd() {
      this.title = "新增数据";
      this.createForm = {
        phoneNumber: "",
        integral: 0,
        cardType: "1",
        balance: 0,
        memberGrade: "",
        labelId: "",
        couponIssueId: "",
      };
      this.open = true;
    },
    handleSubmitLable() {
      updateImportList({
        type: this.handleType,
        id: this.tempId,
        phoneArr: this.tempArr,
      })
        .then((r) => {
          this.getList();
          this.confirmDialog = false;
        })
        .catch((e) => {
          this.msgError("操作失败，请刷新后重试~");
        });
    },
    cancelSubmitLabel() {
      this.getList();
      this.confirmDialog = false;
    },
    translationLabel(id) {
      const label = this.labelList.find((ele) => {
        return id == ele.id;
      });
      if (label == undefined) {
        return "";
      }
      return label.labelName;
    },
    toUnGrade(phoneNumber) {
      const delArr = [];
      if (this.selectedImport.length == 0) {
        delArr.push(phoneNumber);
      } else {
        this.selectedImport.map((ele) => {
          if (!!ele.phoneNumber) {
            delArr.push(ele.phoneNumber);
          }
        });
      }
      this.handleType = 0;
      this.tempArr = delArr;
      this.delHandle();
    },
    toUnLabel(phone) {
      const delArr = [];
      if (this.selectedImport.length == 0) {
        delArr.push(phone);
      } else {
        this.selectedImport.map((ele) => {
          if (!!ele.phoneNumber) {
            delArr.push(ele.phoneNumber);
          }
        });
      }
      this.handleType = 1;
      this.tempArr = delArr;
      this.delHandle();
    },
    toUnIssue(phone) {
      const delArr = [];
      if (this.selectedImport.length == 0) {
        delArr.push(phone);
      } else {
        this.selectedImport.map((ele) => {
          if (!!ele.phoneNumber) {
            delArr.push(ele.phoneNumber);
          }
        });
      }
      this.handleType = 2;
      this.tempArr = delArr;
      this.delHandle();
    },
    upImport(row) {
      this.createForm = row;
      this.open = true;
    },
    delImport(row) {
      const delArr = [];
      if (this.selectedImport.length == 0) {
        delArr.push(row.excelId);
      } else {
        this.selectedImport.map((ele) => {
          if (!!ele.excelId) {
            delArr.push(ele.excelId);
          }
        });
      }
      delImportList(delArr)
        .then((res) => {
          this.getList();
          this.msgSuccess("删除成功！");
        })
        .catch((err) => {
          this.msgError("删除失败，请刷新后重试~");
        });
    },
    delHandle() {
      updateImportList({
        type: this.handleType,
        phoneArr: this.tempArr,
      })
        .then((r) => {
          this.getList();
          this.confirmDialog = false;
        })
        .catch((e) => {
          this.msgError("操作失败，请刷新后重试~");
        });
    },
    selectionChange(selection) {
      console.log("selectionChange", selection);

      this.selectedImport = selection;
    },
    getList() {
      getImportList(this.queryForm)
        .then((res) => {
          if (res.rows == null) {
            this.importList = [];
            this.total = 0;
          } else {
            this.importList = res.rows;
            this.total = res.total;
          }
        })
        .catch((err) => {
          this.msgError("拉取导入的数据列表失败");
        });
    },
    submitExcel() {
      importExcel(this.tempImportList)
        .then((res) => {
          this.tempImportDialog = false;
          this.tipOpen = true;
          this.tipContent = res.msg;
        })
        .catch(() => {
          this.tempImportDialog = false;
          this.msgError("导入失败，请刷新后重试");
        });
    },
    cancelExcel() {
      this.tempImportDialog = false;
    },
    handleQuery() {
      this.queryForm.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    toGrade(phoneAndId) {
      const phoneAndIdArr = phoneAndId.match(/\d{1,}/g);
      const phone = phoneAndIdArr[0];
      const id = phoneAndIdArr[1];

      if (!id || !phone) {
        this.msgError("强拉等级失败，刷新重试~");
        return;
      }

      if (this.selectedImport.length == 0) {
        this.tempArr = [phone];
      } else {
        this.tempArr = [];
        this.selectedImport.map((ele) => {
          this.tempArr.push(ele.phoneNumber);
        });
      }

      this.handleType = 0;
      this.tempId = id;

      this.confirmDialog = true;
    },
    toLabel(phoneAndId) {
      const phoneAndIdArr = phoneAndId.match(/\d{1,}/g);
      const phone = phoneAndIdArr[0];
      const id = phoneAndIdArr[1];

      if (!id || !phone) {
        this.msgError("强拉标签失败，刷新重试~");
        return;
      }

      if (this.selectedImport.length == 0) {
        this.tempArr = [phone];
      } else {
        this.tempArr = [];
        this.selectedImport.map((ele) => {
          this.tempArr.push(ele.phoneNumber);
        });
      }

      this.handleType = 1;
      this.tempId = id;

      this.confirmDialog = true;
    },
    toIssue(phoneAndId) {
      const phoneAndIdArr = phoneAndId.match(/\d{1,}/g);
      const phone = phoneAndIdArr[0];
      const id = phoneAndIdArr[1];

      if (!id || !phone) {
        this.msgError("强拉标签失败，刷新重试~");
        return;
      }

      if (this.selectedImport.length == 0) {
        this.tempArr = [phone];
      } else {
        this.tempArr = [];
        this.selectedImport.map((ele) => {
          this.tempArr.push(ele.phoneNumber);
        });
      }

      this.handleType = 2;
      this.tempId = id;

      this.confirmDialog = true;
    },
    handleUpload(e) {
      const files = e.target.files;
      let file = files[0];
      if (!file) {
        document.getElementById("upload_file").value = null;
        return;
      }
      const fileExt = file.name.split(".").pop().toLocaleLowerCase();
      if (fileExt === "xlsx" || fileExt === "xls") {
        document.getElementById("upload_file").value = null;
        this.readFile(file);
      } else {
        this.msgError("请选择后缀为.xlsx或者.xls的EXCEL文件");
      }
      return false;
    },
    readFile(file) {
      const reader = new FileReader();
      reader.readAsArrayBuffer(file);
      reader.onloadstart = (e) => {
        console.log("onloadstart");
      };
      reader.onprogress = (e) => {
        console.log("onprogress");
        this.progressPercent = Math.round((e.loaded / e.total) * 100);
      };
      reader.onerror = (e) => {
        this.msgError("文件读取出错");
      };
      reader.onload = (e) => {
        console.log("onload");
        const data = e.target.result;
        const { header, results } = excel.read(data, "array");
        //验证excel导入的有效性
        if (!header.includes("phoneNumber")) {
          this.msgError("请使用官方Excel模板导入数据");
          return;
        }

        this.tempImportList = results;
        this.tempImportDialog = true;
      };
    },
  },
};
</script>
<style scoped lang="scss">
.app-container {
  .container {
    .row {
      margin-bottom: 10px;
    }
  }
}
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}
.el-icon-arrow-down {
  font-size: 12px;
}
</style>
